<?php

declare (strict_types=1);

namespace app\beautiful\controller\miniapp;

use app\beautiful\logic\ConDataLogic;
use app\beautiful\logic\MemberCouponLogic;
use app\beautiful\model\CouponModel;

use app\beautiful\model\member\MemberModel;
use app\beautiful\model\miniapp\RecommendAppModel;
use app\beautiful\model\StyleModel;
use app\BaseController;
use app\common\helper\open\OpenPlatformMiniappHelper;
use app\common\logic\TokenLogic;
use app\common\model\RegisterLogsModel;
use app\beautiful\logic\PartnerLogic;
use TencentCloud\Cds\V20180420\Models\DbauditTypesInfo;
use app\common\model\ShopStoreModel;
use think\facade\Db;


class Main extends BaseController {
    public function getRecommendMiniapps(){
        $datas = RecommendAppModel::where([
            ['shop_id','=', $this->request->shopId],
            ['is_delete','=',0]
        ])->order(['recommend_app_id'=>'desc'])->limit($this->request->limit)->select()->toArray();
        return $this->success([
            'miniapps' => $datas
        ]);
    }

    //下放风格基本配置
    public function init() {
        $store_id = $this->request->param('store_id/d',0);
        $lat = $this->request->param('lat');
        $lng = $this->request->param('lng');
        if($store_id == 0) { 
            $where = [
                ['shop_id','=',$this->request->shopId],
                ['is_delete','=',0],
                ['enable','=',1]
            ];
            $store = ShopStoreModel::where($where)->select()->toArray();
            // 计算坐标距离 // 计算坐标距离
            if(!empty($store)) {
                foreach($store as $k => &$v) {
                    $v['distance'] = round(distance($lat,$lng,$v['lat'],$v['lng']),2);
                }
                $sort = array_column($store,'distance');
                array_multisort($sort, SORT_ASC, $store);
                $store = $store[0];
            }else{
                 return $this->error('请设置门店信息');
            }
        }else{
            $store = ShopStoreModel::find($store_id);
        }
        $shopId = $this->request->shopId;
        $style = cache('miniapp_style' . $shopId);
        if (empty($style)) {
            $miniappStyle = StyleModel::find($shopId);
            if (null === $miniappStyle) {
                return $this->error('暂未设置小程序风格');
            }
            $style = $miniappStyle->style;
            cache('miniapp_style' . $shopId, $style, 86400);
        }
        $coupon = Db::name('beautiful_coupon')
            ->where(['type_id'=>4,'status'=>1,'is_delete'=>0,'shop_id'=>$shopId])->value('coupon_money');
        if(!$coupon){
            $coupon = Db::name('beautiful_coupon')
                ->where(['type_id'=>2,'status'=>1,'is_delete'=>0,'shop_id'=>$shopId])->value('coupon_money');
        }
        // 切换店铺
        $return['style']    = $style;
        $return['shopInfo'] = !empty($store) ? $store : $this->request->miniapp;
        $return['coupon'] = intval($coupon);
        return $this->success($return);
    }

    //登录
    public function passport() {
        $code = $this->request->param('code');
        $encryptedData = $this->request->param('encryptedData');
        $iv = $this->request->param('iv');
        if(empty($code) || empty($encryptedData) || empty($iv)){
            return $this->error('登录授权解析失败#01');
        }
        $Openplatform = new OpenPlatformMiniappHelper();
        $datas = $Openplatform->setShopId($this->request->shopId)->getUserInfo([
            'code'          => $code,
            'encryptedData' => $encryptedData,
            'iv'            => $iv,
        ]);
        if (false === $datas) {
            return $this->error('登录授权解析失败');
        }
        $pid = $this->request->param('pid/d');
        $today = date('Y-m-d', $this->request->time()); 
        $is_new = false;
        if (null === $member = MemberModel::where([
                ['shop_id', '=', $this->request->shopId],
                ['mobile', '=', $datas['mobile']],
                ['is_delete','=',0]
            ])->find()) {

         
            $member = new MemberModel();
            $member->shop_id = $this->request->shopId;
            $member->mobile = $datas['mobile'];
            $member->level_id = 0;
            $member->open_id = $datas['openid'];
            $member->nick_name = '未设置'; //防止有特殊字的用户
            // $member->save();
            $rst = $member->save();
            if($rst) {
                $partnerLogic = new PartnerLogic($this->request->shopId);
                $partnerLogic->memberPartner($datas['mobile']);
            }
            //新用户的券
            $new_member_coupon_data=CouponModel::where([
                ['shop_id','=',$this->request->shopId],
                ['type_id','=',2],
                ['status','=',1],
                ['is_delete','=',0],
                ['start_time','<=',$today],
                ['end_time','>=',$today],
            ])->order(['update_time'=>'desc','add_time'=>'desc'])
                ->limit(5)
                ->field('coupon_id,name,coupon_money,money_limit,valid_bg_time,valid_end_time')
                ->select()->toArray();
            if(!empty($new_member_coupon_data)){
                $member_coupon_logic= new MemberCouponLogic($this->request->shopId,$member->member_id);
                foreach ($new_member_coupon_data as $coupon){
                    $member_coupon_logic->getCoupon($coupon,2,1,0);
                }
            }
            //送优惠券
            if(!empty($pid)){
                 $invitation_coupon_data=CouponModel::where([
                    ['shop_id','=',$this->request->shopId],
                    ['type_id','=',4],
                    ['status','=',1],
                    ['is_delete','=',0],
                    ['start_time','<=',$today],
                    ['end_time','>=',$today],
                ])->order(['update_time'=>'desc','add_time'=>'desc'])
                    ->limit(5)
                    ->field('coupon_id,name,coupon_money,money_limit,valid_bg_time,valid_end_time')
                    ->select()->toArray();
                if(!empty($invitation_coupon_data)){
                    $coupon = $invitation_coupon_data[array_rand($invitation_coupon_data,1)] ?? [];
                    if(!empty($coupon)){
                        //被邀请送券
                        $member_coupon_logic= new MemberCouponLogic($this->request->shopId,$member->member_id);
                        $member_coupon_logic->getCoupon($coupon,2,10,0);
                        //邀请送券
                        $member_coupon_logic= new MemberCouponLogic($this->request->shopId,$pid);
                        $member_coupon_logic->getCoupon($coupon,2,9,0);
                    }
                }
            }
            
            //插入注册日志
            $register_logs = new RegisterLogsModel();
            $register_logs->shop_id=$this->request->shopId;
            $register_logs->mobile=$member->mobile;
            $register_logs->save();
            $is_new = true;
        }else{ //非新用户不更新Pid 了
            if(empty($member->open_id)){
                $member->open_id=$datas['openid'];
                $member->save(); 
            }
        }
        //合伙人绑定
        if(!empty($pid)){
            $PartnerLogic = new PartnerLogic($this->request->shopId);
            $PartnerLogic->bindPartner($member->member_id, $pid,$is_new);
        }
       
        $return = [];
        $return['token'] = TokenLogic::getMiniToken($member->member_id);
        return $this->success($return);
    }

    public function getHomeData()
    {
        $params=$this->request->param('params/a',[]);
        if(empty($params)) return $this->success([]);
        foreach ($params as $param){
            if(!isset($param['key'])) return $this->error('参数错误');
            if(empty($param['key'])) return $this->error('参数错误');
            if(!isset($param['num'])) return $this->error('参数错误');
            if(empty($param['num']) || $param['num']<=0 || $param['num']>10) return $this->error('参数错误');
        }
        $ConDataLogic = new ConDataLogic($this->request->shopId,$this->request->memberId);
        $datas=$ConDataLogic->getData($params);
        return $this->success(['datas'=>$datas]);
    }
    
    public function getStoreList() {
        $lat = $this->request->param('lat');
        $lng = $this->request->param('lng');
        $where = [
            ['shop_id','=',$this->request->shopId],
            ['is_delete','=',0],
            ['enable','=',1],
        ];
        $field='*';
        $order=['is_main'=>'asc','add_time'=>'desc'];
        $store = ShopStoreModel::where($where)->field($field)->order($order)->select()->toArray();
        
        // 计算坐标距离
        if(!empty($store)) {
            foreach($store as $k => &$v) {
                $v['distance'] = round(distance($lat,$lng,$v['lat'],$v['lng']),2);
            }
            
            $sort = array_column($store,'distance');
            array_multisort($sort, SORT_ASC, $store);
        }
        return $this->success(['datas'=>$store]);
    }
    
    public function getStoreShop(){
        $id = $this->request->param('id/d',0);
        if($id == 0) { 
            $where = [
                ['shop_id','=',$this->request->shopId],
                ['is_delete','=',0],
                ['enable','=',1],
                ['is_main','=',1]
            ];
            $store = ShopStoreModel::where($where)->find();
        }else{
            $store = ShopStoreModel::find($id);
        }
        return $this->success(['shopInfo'=>$store]);
    }
}
